import os
import ConfigParser
import MySQLdb
from lib import constants as C
from lib.utils.read_settings import MySQLSettings as MS
from lib.utils.display import Display

__all__ = ['mysql', 'load_mysql']

MS = MS()
display = Display()

class mysql(object):
    def connect(self):
        conn = None
        try:
            if not conn:
                conn = MySQLdb.connect(MS.mysql_host, MS.mysql_username, MS.mysql_password, MS.mysql_database, unix_socket=MS.mysql_socket)
        except Exception as e:
            print e
            conn = None
        finally:
            return conn

    def ExecuteFile(self, file):
        """ Execute SQL Script and Return Status """
        try:
            conn = self.connect()
            cur = conn.cursor()
            if conn:
                file = C.CONFIG_PATH + 'sql/' + file
                with open(file, 'r+') as f:
                    sql_list = f.read().split(';')[:-1]
                    sql_list = [x.replace('\n', ' ') if '\n' in x else x for x in sql_list]
                if sql_list:
                    for sql in sql_list:
                        cur.execute(sql)
                    conn.commit()
                    status = 'success'
                else:
                    print "error: maybe missing ';' in %s" % file
                    status = 'no sql'
            else:
                status = 'no conn'
        except Exception as e:
            conn.rollback()
            print e
            status = 'false'
        finally:
            conn.close()
            return status


def main():
    test_mysql = mysql()
    print test_mysql.ExecuteFile('create_table_hosts.sql')


if __name__ == '__main__':
    main()
